package cn.zhentao.controller;

import cn.zhentao.pojo.TPurchaseOrder;
import cn.zhentao.service.TPurchaseOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private TPurchaseOrderService orderService;

    /**
     * 创建订单
     * 前端需传递：买家ID、卖家ID、车辆ID、定金金额、总金额
     */
    @PostMapping("/create")
    public Map<String, Object> createOrder(
            @RequestParam("buyerId") Long buyerId,
            @RequestParam("sellerId") Long sellerId,
            @RequestParam("carId") Long carId,
            @RequestParam("depositAmount") BigDecimal depositAmount,
            @RequestParam("totalAmount") BigDecimal totalAmount
    ) {
        // 构建订单对象（状态默认为1-待付定金，创建时间自动生成）
        TPurchaseOrder order = new TPurchaseOrder();
        order.setBuyerId(buyerId);
        order.setSellerId(sellerId);
        order.setCarId(carId);
        order.setDepositAmount(depositAmount);
        order.setTotalAmount(totalAmount);
        order.setOrderStatus(1); // 待付定金
        order.setCreateTime(new Date());

        // 调用服务层创建订单（生成订单编号等逻辑在服务层实现）
        return orderService.createOrder(order);
    }

    /**
     * 查询待支付订单（包含待付定金和待付全款）
     * 前端可传递买家ID筛选个人待支付订单
     */
    @GetMapping("/pendingPayment")
    public List<TPurchaseOrder> getPendingPaymentOrders(
            @RequestParam(value = "buyerId", required = false) Long buyerId
    ) {
        // 订单状态：1-待付定金，2-待付全款
        return orderService.getOrdersByStatusAndBuyer(
                new byte[]{1, 2}, buyerId
        );
    }

    /**
     * 取消订单
     * 需传递订单ID和取消原因，仅允许取消待支付状态的订单
     */
    @PostMapping("/cancel")
    public Map<String, Object> cancelOrder(
            @RequestParam("orderId") Long orderId,
            @RequestParam("cancelReason") String cancelReason
    ) {
        return orderService.cancelOrder(orderId, cancelReason);
    }

    /**
     * 查询已取消订单
     * 可按买家ID或卖家ID筛选
     */
    @GetMapping("/cancelled")
    public List<TPurchaseOrder> getCancelledOrders(
            @RequestParam(value = "buyerId", required = false) Long buyerId,
            @RequestParam(value = "sellerId", required = false) Long sellerId
    ) {
        // 假设取消订单状态为0（需与实际业务中状态定义一致）
        return orderService.getOrdersByStatusAndUser(
                (byte) 0, buyerId, sellerId
        );
    }

    /**
     * 订单支付（定金或全款，统一更新支付时间和状态）
     * 前端传递订单ID和支付类型（1-定金，2-全款）
     */
    @PostMapping("/pay")
    public Map<String, Object> payOrder(
            @RequestParam("orderId") Long orderId,
            @RequestParam("payType") Integer payType // 1-定金，2-全款
    ) {
        // 支付后状态变更：
        // 付定金后→待付全款（2），付全款后→待交付（3）
        byte targetStatus = (payType == 1) ? (byte) 2 : (byte) 3;
        return orderService.updateOrderAfterPayment(orderId, targetStatus, new Date());
    }

    /**
     * 标记订单为已完成（交付后调用）
     * 仅允许对待交付状态（3）的订单操作
     */
    @PostMapping("/complete")
    public Map<String, Object> completeOrder(
            @RequestParam("orderId") Long orderId
    ) {
        return orderService.updateOrderStatus(orderId, (byte) 4); // 4-已完成
    }

    /**
     * 查询已完成订单
     * 可按买家或卖家筛选
     */
    @GetMapping("/completed")
    public List<TPurchaseOrder> getCompletedOrders(
            @RequestParam(value = "buyerId", required = false) Long buyerId,
            @RequestParam(value = "sellerId", required = false) Long sellerId
    ) {
        return orderService.getOrdersByStatusAndUser(
                (byte) 4, buyerId, sellerId
        );
    }
}